package common;
import java.io.IOException;  
import java.io.Reader;  

import org.apache.ibatis.io.Resources;  
import org.apache.ibatis.session.SqlSession;  
import org.apache.ibatis.session.SqlSessionFactory;  
import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  
/** 
 * 宸ュ叿绫� 
 */  
public class MybatisUtil {  
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();  
    private static SqlSessionFactory sqlSessionFactory;  
    /** 
     * 鍔犺浇浣嶄簬src/mybatis.xml閰嶇疆鏂囦欢 
     */  
    static{  
        try {  
            Reader reader = Resources.getResourceAsReader("mybatis-cfg.xml");  
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  
        } catch (IOException e) {  
            e.printStackTrace();  
            throw new RuntimeException(e);  
        }  
    }  
    /** 
     * 绂佹澶栫晫閫氳繃new鏂规硶鍒涘缓  
     */  
    private MybatisUtil(){}  
    /** 
     * 鑾峰彇SqlSession 
     */  
    public static SqlSession getSqlSession(){  
        //浠庡綋鍓嶇嚎绋嬩腑鑾峰彇SqlSession瀵硅薄  
        SqlSession sqlSession = threadLocal.get();  
        //濡傛灉SqlSession瀵硅薄涓虹┖  
        if(sqlSession == null){  
            //鍦⊿qlSessionFactory闈炵┖鐨勬儏鍐典笅锛岃幏鍙朣qlSession瀵硅薄  
            sqlSession = sqlSessionFactory.openSession();  
            //灏哠qlSession瀵硅薄涓庡綋鍓嶇嚎绋嬬粦瀹氬湪涓�璧�  
            threadLocal.set(sqlSession);  
        }  
        //杩斿洖SqlSession瀵硅薄  
        return sqlSession;  
    }  
    
    public static <T>T getMapper(Class<T> class1) {
    	return getSqlSession().getMapper(class1);
    }
    /** 
     * 鍏抽棴SqlSession涓庡綋鍓嶇嚎绋嬪垎寮� 
     */  
    public static void closeSqlSession(){  
        //浠庡綋鍓嶇嚎绋嬩腑鑾峰彇SqlSession瀵硅薄  
        SqlSession sqlSession = threadLocal.get();  
        //濡傛灉SqlSession瀵硅薄闈炵┖  
        if(sqlSession != null){  
            //鍏抽棴SqlSession瀵硅薄  
            sqlSession.close();  
            //鍒嗗紑褰撳墠绾跨▼涓嶴qlSession瀵硅薄鐨勫叧绯伙紝鐩殑鏄GC灏芥棭鍥炴敹  
            threadLocal.remove();  
        }  
    }  
}